# coding=utf-8
from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request
from sqlalchemy.sql.functions import user
from werkzeug.utils import redirect

from info import constants
from info import db
from info.models import Category, News
from info.modules.profile import profile_blu
from info.utils.captcha.image_store import storage
from info.utils.common import user_login_data
from info.utils.response_code import RET



@profile_blu.route("/info")
@user_login_data
def get_user_info():
    """
    获取用户信息
    1. 获取当前登录的用户模型
    2. 返回模型中指定内容
    :return:
    """

    if not g.user:
        return redirect("/")  # 重定向到首页

    data = {
        "user":g.user.to_dict()
    }

    return render_template("news/user.html", data=data)


@profile_blu.route("/base_info", methods=["GET", "POST"])
@user_login_data
def base_info():
    """用户基本信息"""
    if request.method == "GET":
        return render_template("news/user_base_info.html", data={"user": g.user.to_dict()})

    # 修改用户数据
    # 1. 取到传入参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 2. 校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user= g.user
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route("/pic_info", methods=["POST", "GET"])
@user_login_data
def pic_info():
    if request.method == "GET":
        return render_template("news/user_pic_info.html",data={"user": g.user.to_dict()})

    # 如果是post表示修改图像
    # 1. 取到上传的图片
    try:
        file = request.files.get("avatar")
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")


@profile_blu.route("/pass_info", methods=["POST", "GET"])
@user_login_data
def pass_info():
    if request.method == "GET":
        return render_template("news/user_pass_info.html")

    # 1. 获取到传入参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not g.user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    # 2. 更新数据
    g.user.password = new_password
    try:
        db.session.commit()
    except Exception as ret:
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route('/collection')
@user_login_data
def user_collection():

    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as ret:
        current_app.logger.error(ret)
        p = 1

    collections = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = g.user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as ret:
        current_app.logger.error(ret)

    collection_dict_li = [news.to_basic_dict() for news in collections]
    data = {
        "collections":collection_dict_li,
        "current_page":current_page,
        "total_page":total_page
    }
    return render_template('news/user_collection.html', data=data)


@profile_blu.route("/news_release", methods=["GET", "POST"])
@user_login_data
def news_release():
    """发布新闻"""

    if request.method == "GET":
        categories = []
        try:
            # 获取所有的分类数据
            categories = Category.query.all()
        except Exception as ret:
            current_app.logger.error(ret)

        categories_dicts = [category.to_dict() for category in categories]
        # 移除最新分类
        categories_dicts.pop(0)
        data = {
            "categories":categories_dicts
        }
        #返回内容
        return render_template("news/user_news_release.html", data=data)

    # POST请求
    # 1.获取要提交的数据
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    if not all([title, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误.")

    # 2. 将标题图片上传到七牛
    try:
        index_image_data = index_image.read()
        key = storage(index_image)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误..")

    # 3. 初始化新闻模型, 并设置相关数据
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 带审核状态: 1
    news.status = 1

    # 4. 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as ret:
        current_app.logger.error(ret)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 5. 返回数据
    return jsonify(errno=RET.OK, errmsg="发布成功, 等待审核")




